<template>
  <view class="mt-upload-file">
    <view v-for="(item, index) in fileUrlList" :key="index" class="file-area flex flex-col">
      <view class="file-area-item flex items-center py-24rpx">
        <view class="flex items-center flex-1 min-w-0">
          <view class="w-50rpx"><uv-icon size="16" :name="fileExtension(item.name)"></uv-icon></view>
          <view class="file-name w-540rpx ml-16rpx clamp1">
            <text class="text-#1C213E fw-400 text-28rpx">{{ item.name }}</text>
          </view>
        </view>
        <uv-icon size="16" name="close" class="ml-16rpx mt-4rpx" @click="clear(index)"></uv-icon>
      </view>
      <uv-line v-show="index != fileUrlList.length - 1" color="#e6e6e6" class="mt-24rpx"></uv-line>
    </view>

    <lsj-upload
      ref="lsjUploadRef"
      :debug="false"
      :html-url="htmlUrl"
      :multiple="false"
      :width="width"
      :height="height"
      :count="limit"
      :size="size"
      :option="options"
      :instantly="false"
      :class="{ 'lsj-upload': true, 'justify-around': fileUrlList && fileUrlList.length > 0, 'bg-1': fileUrlList && fileUrlList.length > 0 }"
      @change-file="onChange"
      @upload-end="onuploadEnd"
      @permission-success="handlePermissionSuccess"
    >
      <view v-if="fileUrlList && fileUrlList.length > 0" class="flex items-center">
        <uv-icon size="40rpx" color="#007bff" name="plus"></uv-icon>
        <text class="ml-32rpx text-#007BFF fw-400 text-28rpx">继续上传</text>
      </view>
      <view v-else class="btn" :style="{ width: width, height: height }">
        <uv-icon size="40rpx" name="https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-upload-plus.svg"></uv-icon>
      </view>
    </lsj-upload>
    <text v-show="!fileUrlList || fileUrlList.length <= 0" class="mt-24rpx fw-400 text-24rpx text-#ADB0BD">支持上传word，PDF，PNG等各类文件。</text>
  </view>
</template>

<script name="MtUploadFile" setup>
import { uploadFileBase, getFileExt, getAliOssKey } from '@/utils/tools';
import userStore from '@/store/user';

const props = defineProps({
  width: {
    type: String,
    default: '128rpx'
  },
  height: {
    type: String,
    default: '128rpx'
  },
  limit: {
    type: Number,
    default: 200
  },
  size: {
    // 文件大小上限(M)
    type: Number,
    default: 20
  },
  ossPath: {
    // 上传到阿里云的路径，传一个文件夹目录名称
    type: String,
    default: 'upload'
  }
});

// 文件图标
const iconFile = {
  'pdf': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-pdf.svg',
  'mp4': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-mp4.svg',
  'doc': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-word.svg',
  'docx': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-word.svg',
  'xls': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-excel.svg',
  'xlsx': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-excel.svg',
  'png': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-png.svg',
  'svg': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-png.svg',
  'jpg': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-jpg.svg',
  'jpeg': 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-jpg.svg'
};

const htmlUrl = ref(import.meta.env.VITE_OSS_HTML_URL);

// 判断文件格式现在对应的后缀
const fileExtension = (fileName) => {
  return iconFile[getFileExt(fileName)];
};

const options = ref({
  url: '#',
  name: 'file',
  formData: {
    'orderId': 1000
  }
});

const fileList = ref([]);
const fileUrlList = defineModel({ type: Array, default: () => [] });
const lsjUploadRef = ref();

function handlePermissionSuccess(res) {
  uni.setStorage({
    key: res.permission,
    data: Number(res.result)
  });
}
// 某文件上传结束回调(成功失败都回调)
const onuploadEnd = (item, childId) => {
  // #ifdef APP
  if (item.type === 'success') {
    fileUrlList.value.push({
      name: item.name,
      url: fullUrl.value
    });
  }
  lsjUploadRef.value.clear();
  uni.hideLoading();
  // #endif
};

// 文件选择回调
// 是否在上传中
let uploader = ref(false);
const onChange = async (files, childId) => {
  try {
    uni.showLoading({
      title: '文件上传中...',
      mask: true
    });
    fullUrl.value = '';
    fileList.value = [...files];
    // #ifdef APP
    appUpload();
    // #endif

    // #ifdef H5
    if (!uploader.value) {
      uploader.value = true;
      await h5Upload();
      lsjUploadRef.value.clear();
      uploader.value = false;
      uni.hideLoading();
    }
    // #endif
  } catch (error) {
    uni.hideLoading();
  }
};

// 手动上传
// 上传后的完整地址
const fullUrl = ref('');
const appUpload = async () => {
  try {
    const user = userStore();

    for (const file of fileList.value) {
      let now = new Date().getTime();
      let ossPath = `mtym-app/${props.ossPath}/${user.userInfo.providerId}/${now}/${file[1].name}`;

      const ossKeyObj = await getAliOssKey(props.ossPath);
      lsjUploadRef.value.setData('url', ossKeyObj.host);
      lsjUploadRef.value.setData('formData', {
        key: ossPath,
        ...ossKeyObj
      });
      fullUrl.value = ossKeyObj.host + ossPath;
      setTimeout(() => {
        lsjUploadRef.value.upload(file[1].name);
      }, 500);
    }
  } catch (error) {
    uni.hideLoading();
  }
};

async function h5Upload() {
  for (const file of fileList.value) {
    let result = await uploadFileBase(
      {
        name: file[1].name,
        url: file[1].path
      },
      props.ossPath
    );

    fileUrlList.value.push({
      name: file[1].name,
      url: result
    });
  }
}

// 移除某个文件
const clear = (index) => {
  fileUrlList.value.splice(index, 1);
};

// 更新当前页所有上传组件在页面中的位置
function changePosition() {
  nextTick(() => {
    uni.$emit('$upload-show', {});
  });
}

defineExpose({
  changePosition
});
</script>

<style lang="scss" scoped>
.mt-upload-file {
  display: flex;
  flex-direction: column;

  .file-area {
    .file-name {
      word-break: break-all;
    }
  }

  .btn {
    background-color: #f5f5f5;
    color: #fff;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
  }

  .lsj-upload {
    display: flex;
  }

  .bg-1 {
    background: rgba(0, 123, 255, 0.1);
    border-radius: 0px 0px 0px 0px;
    height: 2.5rem !important;
  }

  :deep(.lsj-file) {
    width: 100% !important;
    display: flex;
    align-items: center;
    .hFile {
      width: 200rpx !important;
      height: 96rpx;
      display: flex;
      align-items: center;
    }
  }
}
</style>
